'use strict';

const APPID = 'cc69f09d';
const apiSecret = 'ZDQ3YjFmNmNmOWRmOGM0MmI1ZDVmYmRh';
const apiKey = '09a56431edd578b96f01ae2e2312e638';
const requestUrl = 'https://api.xf-yun.com/v1/private/sf8e6aca1';
const crypto = require('crypto');

function buildRequestUrl() {
	const date = new Date().toUTCString();
	const host = 'api.xf-yun.com';

	const requestLine = `host: ${host}\ndate: ${date}\nPOST /v1/private/sf8e6aca1 HTTP/1.1`;
	const hmac = crypto.createHmac('sha256', apiSecret);
	hmac.update(requestLine);
	const sha = hmac.digest('base64');

	const authorization =
		`api_key="${apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${sha}"`;
	const authBase = Buffer.from(authorization).toString('base64');
	const strr =
		`${requestUrl}?authorization=${encodeURIComponent(authBase)}&host=${encodeURIComponent(host)}&date=${encodeURIComponent(date)}`
	console.log(strr);
	return strr;
}


function buildParam(img) {
	// const imageBase64 = fs.readFileSync(IMAGE_PATH).toString('base64');

	const param = {
		header: {
			app_id: APPID,
			status: 3,
		},
		parameter: {
			sf8e6aca1: {
				category: 'ch_en_public_cloud',
				result: {
					encoding: 'utf8',
					compress: 'raw',
					format: 'json',
				},
			},
		},
		payload: {
			sf8e6aca1_data_1: {
				encoding: 'jpg',
				status: 3,
				image: img,
			},
		},
	};

	return JSON.stringify(param);
}


exports.main = async (event, context) => {
	// console.log(buildParam(event.img));
	const res = await uniCloud.httpclient.request(buildRequestUrl(), {
		method: "POST",
		headers: {
			"Content-type": "application/json"
		},
		data: buildParam(event.img),
		dataType: 'json'
	})
	if (res.status == 200) {
		return res.data
	}
	return res
};